package com.shangdiao.sd_server.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.shangdiao.sd_server.util.KdJedisPool;

@Service
public class RedisService {


    //@Autowired
    //private JedisPool jedisPool;
    
    private JedisPool jedisPool = KdJedisPool.getJedisPool();
    
    
    /**
     * 为key设置生存时间
     * @param key
     * @param value
     * @param seconds 单位：秒
     */
    public void set(String key, String value, int seconds){
    	try(Jedis jedis = jedisPool.getResource()) {
    		jedis.set(key, value);
    		jedis.expire(key, seconds);
    	} 
    }
    
    public void set(String key, String value){
    	try(Jedis jedis = jedisPool.getResource()) {
    		jedis.set(key, value);
    	} 
    }
    
    public String get(String key){
    	try(Jedis jedis = jedisPool.getResource()) {
    		String value = jedis.get(key);
    		return value;
    	} 
    }
    
    public void del(String key){
    	try(Jedis jedis = jedisPool.getResource()) {
    		jedis.del(key);
    	} 
    }
        
    
    
    //序列化  
    public byte[] serialize(Object object){  
    	ObjectOutputStream objectOutputStream = null;  
    	ByteArrayOutputStream byteArrayOutputStream = null;  
    	try {  
    		byteArrayOutputStream = new ByteArrayOutputStream();  
    		objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);  
    		objectOutputStream.writeObject(object);  
    		byte[] bytes = byteArrayOutputStream.toByteArray();  
            return bytes;  
    	} catch (Exception e) {  
    		e.printStackTrace();  
    	}  
    	return null;  
    }  
    
    
    // 反序列化  
    public Object deSeialize(byte[] bytes) {  
    	ByteArrayInputStream byteArrayOutputStream = null;  
    	try {  
    		byteArrayOutputStream = new ByteArrayInputStream(bytes);  
    		ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayOutputStream);  
    		return objectInputStream.readObject();  
    	} catch (Exception e) {  
    		e.printStackTrace();
    	}  
    	return null;
    }
    
    
    
}
